package com.starchen.optimalselection.common.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.starchen.optimalselection.common.model.*;
import com.starchen.optimalselection.common.service.*;
import com.starchen.optimalselection.common.utils.PageUtils;
import com.starchen.optimalselection.common.mapper.SpuInfoMapper;
import com.starchen.optimalselection.common.model.vo.BaseAttrs;
import com.starchen.optimalselection.common.model.vo.Images;
import com.starchen.optimalselection.common.model.vo.Skus;
import com.starchen.optimalselection.common.model.vo.SpuSaveVo;
import com.starchen.optimalselection.common.model.vo.Attr;
import com.starchen.optimalselection.common.model.vo.SpuQueryVo;
import com.starchen.optimalselection.common.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoMapper, SpuInfo> implements SpuInfoService {

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private SpuImagesService spuImagesService;

//    @Autowired
//    private AttributeValueService attributeValueService;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

//    @Autowired
//    private WareSkuService wareSkuService;

    @Override
    public ResultPage queryPage(SpuQueryVo spuQueryVo) {
        String key =  spuQueryVo.getKeyword();
        QueryWrapper<SpuInfo> queryWrapper = new QueryWrapper<>();
        if(StringUtils.hasText(key)){
            queryWrapper.like("spu_name",key);
        }

        Long catId =  spuQueryVo.getCategoryId();
        if(catId != null){
            queryWrapper.eq("category_id",catId);
        }

        Long brandId =  spuQueryVo.getBrandId();
        if(brandId != null){
            queryWrapper.eq("brand_id",brandId);
        }

        Integer publishStatus =  spuQueryVo.getPublishStatus();
        if(publishStatus != null){
            queryWrapper.eq("publish_status",publishStatus);
        }

        IPage<SpuInfo> page = baseMapper.selectPage(PageUtils.getPage(spuQueryVo.getPageIndex(),spuQueryVo.getPageSize()), queryWrapper);
        return new ResultPage(page);
    }

    /**
     * 发布商品
     * @param spuSaveVo
     */
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo spuSaveVo) {
        //1、保存spu基本信息 pms_spu_info 1
        SpuInfo spuEntity = new SpuInfo();
        BeanUtils.copyProperties(spuSaveVo,spuEntity);

        spuEntity.setCreateTime(new Date());
        baseMapper.insert(spuEntity);

        //2、保存Spu的描述大图片 pms_spu_info_desc 1
        List<String> decript = spuSaveVo.getDescript();
        SpuInfoDesc descEntity = new SpuInfoDesc();
        descEntity.setSpuId(spuEntity.getId());
        if(decript != null)
            descEntity.setDescript(String.join(",",decript));

        spuInfoDescService.save(descEntity);

        //3、保存spu的图片集 pms_spu_images
        List<String> images = spuSaveVo.getImages();
        spuImagesService.saveImages(spuEntity.getId(),images);

        //4、保存spu的规格参数;pms_product_attr_value
        List<BaseAttrs> baseAttrs = spuSaveVo.getBaseAttrs();

        List<AttributeValue> collect = baseAttrs.stream().map(attr -> {
            AttributeValue valueEntity = new AttributeValue();
            valueEntity.setAttrId(attr.getAttrId());
            valueEntity.setAttrName(attr.getAttrName());
            valueEntity.setAttrValue(attr.getAttrValues());
            valueEntity.setQuickShow(attr.getShowDesc());
            valueEntity.setSpuId(spuEntity.getId());

            return valueEntity;
        }).collect(Collectors.toList());

        //attributeValueService.saveAttributeValues(collect);

        //5、保存当前spu对应的所有sku信息；
        List<Skus> skus = spuSaveVo.getSkus();
        if(skus!=null && skus.size()>0){
            skus.forEach( item -> {
                String defaultImg = "";
                for (Images image : item.getSkuImages()) {
                    if(image.getDefaultImg() == 1){
                        defaultImg = image.getImgUrl();
                    }
                }
                SkuInfo skuInfoEntity = new SkuInfo();
                BeanUtils.copyProperties(item,skuInfoEntity);
                skuInfoEntity.setBrandId(spuEntity.getBrandId());
                skuInfoEntity.setCategoryId(spuEntity.getCategoryId());
                skuInfoEntity.setSpuId(spuEntity.getId());
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                //5.1）、sku的基本信息；pms_sku_info
                skuInfoService.saveSkuInfo(skuInfoEntity);

                Long skuId = skuInfoEntity.getId();

                List<SkuImages> imagesEntities = item.getSkuImages().stream().map(img -> {
                    SkuImages skuImagesEntity = new SkuImages();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    return skuImagesEntity;
                }).filter(entity->{
                    //返回true就是需要，false就是剔除 没有图片路径的无需保存
                    return StringUtils.hasText(entity.getImgUrl());
                }).collect(Collectors.toList());
                //5.2）、sku的图片信息；pms_sku_image
                skuImagesService.saveBatch(imagesEntities);

                List<Attr> attr = item.getAttr();
                List<SkuSaleAttrValue> skuSaleAttrValueEntities = attr.stream().map(a -> {
                    SkuSaleAttrValue attrValueEntity = new SkuSaleAttrValue();
                    BeanUtils.copyProperties(a, attrValueEntity);
                    attrValueEntity.setSkuId(skuId);
                    return attrValueEntity;
                }).collect(Collectors.toList());
                //5.3）、sku的销售属性信息：pms_sku_sale_attr_value
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);

                // //5.4）、sku的优惠、满减等信息；gulimall_sms->sms_sku_ladder\sms_sku_full_reduction\sms_member_price
//                SkuReductionTo skuReductionTo = new SkuReductionTo();
//                BeanUtils.copyProperties(item,skuReductionTo);
//                skuReductionTo.setSkuId(skuId);
//                if(skuReductionTo.getFullCount() >0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal("0")) == 1){
//                    R r1 = couponFeignService.saveSkuReduction(skuReductionTo);
//                    if(r1.getCode() != 0){
//                        log.error("远程保存sku优惠信息失败");
//                    }
//                }

            });
        }
    }

    @Override
    public void statusUp(Long id) {

        /*
        List<SkuInfo> skuInfoList = skuInfoService.getSkusBySpuId(id);

        //获取所有skuid 查询库存准备
        List<Long> skuIds = skuInfoList.stream().map(SkuInfo::getId).collect(Collectors.toList());


        // TODO 4.查询当前sku所有可以被用来检索的规格属性
        // 2.5 设置检索属性集，由于所有sku公用一个spu。所以可以先查出attrs。后直接设置。避免多次查询
        //查询规格属性值
        // 查出该spu所有规格属性中可以用于检索的那些属性的值（规格属性的值）
        List<AttributeValue> baseAttrs = attributeValueService.baseAttrlistforspu(id);

        List<Long> attrIds = baseAttrs.stream().map(AttributeValue::getAttrId).collect(Collectors.toList());
        //再根据id去得到这些attr的详细信息,得到可以被检索的属性
        List<Attribute> searchAttrs = attributeService.selectAttrIds(attrIds);

        // 从中得到可以用于检索的那些attrId
        List<Long> searchIds = searchAttrs.stream().map(attr -> attr.getId()).collect(Collectors.toList());
        Set<Long> searchAttrIdSet = new HashSet<>(searchIds);
        // 再根据这个id集合，去过滤出刚查出的此spu下的所有attr。选出可检索的那些
        List<SkuESModel.Attrs> attrs = baseAttrs.stream().filter(item -> searchAttrIdSet.contains(item.getAttrId())).map(item -> {
            SkuESModel.Attrs attr = new SkuESModel.Attrs();
            attr.setAttrId(item.getAttrId());
            attr.setAttrName(item.getAttrName());
            attr.setAttrValue(item.getAttrValue());
            // 转成SkuESmodel中需要的数据
            return attr;
        }).collect(Collectors.toList());

        // 2.6 调用gulimall-ware服务查询此sku是否有库存
        // 如果每个sku都去调用一次远程服务，消耗太大，让远程服务一次查出全部sku的库存信息
        // TODO 1.查询是否有库存
        List<SkuHasStockVo> hasStock = wareSkuService.getSkusHasStock(skuIds);

        Map<Long,Boolean> collect = hasStock.stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, item -> item.getHasStock()));

        List<SkuESModel> uoProducts = skuInfoList.stream().map(sku -> {
            SkuESModel skuESModel = new SkuESModel();
            // 2.1 基本属性拷贝
            BeanUtils.copyProperties(sku, skuESModel);

            // 2.2 不同属性名处理
            skuESModel.setSkuPrice(sku.getPrice());
            skuESModel.setSkuImg(sku.getSkuDefaultImg());

            // TODO 1.库存
            skuESModel.setHasStock(collect.get(sku.getId()));
            // TODO 2.热度评分
            skuESModel.setHotScore(0L);

            // TODO 3.品牌和分类
            // 2.3 设置brand相关内容
            Brand brandEntity = brandService.getById(sku.getBrandId());
            if (brandEntity != null) {
                skuESModel.setBrandName(brandEntity.getName());
                skuESModel.setBrandImg(brandEntity.getLogo());
            }

            // 2.4 设置category相关内容
            Category categoryEntity = categoryService.getById(sku.getCategoryId());
            if (categoryEntity != null) {
                skuESModel.setCatelogName(categoryEntity.getName());
            }
            // 2.5 设置检索属性集--------
            skuESModel.setAttrs(attrs);

            return skuESModel;
        }).collect(Collectors.toList());

        // 4. 修改该spu的状态为已上架
//        R r = searchFeignService.productStatusUp(uoProducts);
        SpuInfo spuInfo = new SpuInfo();
        spuInfo.setId(id);
        spuInfo.setPublishStatus(ProductConstant.StatusEnum.SPU_UP.getCode());
        baseMapper.updateById(spuInfo);

         */
    }

}